from django.shortcuts import render
from django.http import JsonResponse
from system.models import Menu,Role
from django.contrib.auth.decorators import login_required
from utils.findButtonPer import findButtonPermission
def menu_page(request):
    # 这里进行判断权限部分
    role_obj = request.user.role.first()
    result = findButtonPermission(role_obj=role_obj,key='menu')
    return render(request, 'system/menu/menu.html',result)

def menuAdd_page(request):
    return render(request, 'system/menu/insert.html')

def menuEdit_page(request):
    return render(request, 'system/menu/edit.html')



@login_required()
def getMenuData(request):
    try:
        menu_list = Menu.objects.all()
        list_menu=[]
    except Exception as e:
        return JsonResponse({'code': 4000, 'msg': '查询数据失败！'})
    for i in menu_list:
        dict = {}
        dict['id'] = i.id
        dict['icon'] = i.icon
        dict['title'] = i.name 
        dict['path'] = i.path 
        dict['key'] = i.key 
        dict['spread'] = 'true'
        dict['sort'] = i.sort
        dict['menu_type'] = i.menu_type
        if i.parent_id is not None:
            dict['parent'] = int(i.parent_id)
        else:
            dict['parent'] = None
        list_menu.append(dict)
    res = []
    for con in list_menu:
        res.append(con)
    Result = {'code': 0, 'msg': '成功！', 'data': res}
    return JsonResponse(Result)

@login_required()
def listMenuButtonData(request,key):
    try:
        menu_list = Menu.objects.all()
        list_menu = []
    except Exception as e:
        return JsonResponse({'code': 4000, 'msg': '查询数据失败！'})
    # 通过用户key判断
    if key !='none':
        r_obj = Role.objects.get(key=key)
        for i in menu_list:
            if r_obj.admin == True:
            # 全部是root
                dict1 = {}
                dict1['id'] = i.id
                dict1['title'] = i.name 
                if i.parent_id is not None:
                    dict1['parent'] = int(i.parent_id)
                else:
                    dict1['parent'] = None
                dict1['selected'] = True
                list_menu.append(dict1)
            else:
                # 假如不是root，这里需要判断
                has_menu = r_obj.menu.all()
                for k in menu_list:
                    dict1 = {}
                    dict1['id'] = k.id
                    dict1['title'] = k.name 
                    if i.parent_id is not None:
                        dict1['parent'] = int(i.parent_id)
                    else:
                        dict1['parent'] = None
                    for i in has_menu:
                        if k.id == i.id:
                            dict1['selected'] = True
                    list_menu.append(dict1)
    else:
        for i in menu_list:
            dict1 = {}
            dict1['id'] = i.id
            dict1['title'] = i.name 
            if i.parent_id is not None:
                dict1['parent'] = int(i.parent_id)
            else:
                dict1['parent'] = None
            list_menu.append(dict1)
    res = []
    for contact in list_menu:
        res.append(contact)
    Result = {'code': 0, 'msg': '成功！', 'data': res}
    return JsonResponse(Result)



@login_required()
def addMenuData(request):
    get_name = request.POST.get('name')
    # 这里前端获取下拉框的时候，传上来默认就是名字就叫select
    get_parent = request.POST.get('menu_pid')
    get_path = request.POST.get('path')
    get_menu_type = request.POST.get('menu_type')
    get_key = request.POST.get('key')
    if get_menu_type == 2 and get_key is None:
        return JsonResponse({'code': 4001, 'msg': '按钮必须拥有key!'})
    get_icon = request.POST.get('icon')
    get_sort = request.POST.get('sort')
    get_description = request.POST.get('description')
    try:
        keys = Menu.objects.create(name=get_name,path=get_path,menu_type=get_menu_type,parent_id=int(get_parent),
        icon=get_icon,sort=get_sort,key=get_key,description=get_description,creator_id=request.user.id,dept_belong_id=request.user.dept.id)
    except Exception as e:
        print(e)
        return JsonResponse({'code': 4002, 'msg': '创建新的菜单失败，请联系管理员！'})
    Result = {'code': 0, 'msg': '创建新的菜单成功'}
    return JsonResponse(Result)

@login_required()
def editMenuData(request,id):
    path = request.POST.get('path')
    name = request.POST.get('name')
    parent = request.POST.get('select') #这里前段插件不知道为什么自动命名为select，应该是可以改的
    icon = request.POST.get('icon')
    sort = request.POST.get('sort')
    menu_type = request.POST.get('menu_type')
    description = request.POST.get('remark_describe')
    try:
        Menu.objects.filter(pk=id).update(path=path,name=name,parent_id=parent,icon=icon,sort=sort,menu_type=menu_type,
        description=description,modifier=request.user.id)
    except Exception as e:
        return JsonResponse({'code': 4002, 'msg': '修改新的菜单失败，请联系管理员！'})
    Result = {'code': 0, 'msg': '修改菜单成功'}
    return JsonResponse(Result)

@login_required()
def delMenuData(request,id):
    try:
        menu_obj = Menu.objects.get(pk=id)
    except Exception as e:
        return JsonResponse({'code': 202, 'msg': '未找到删除对象！'})
    # 这里得判断一下是否存在关联
    menu_count = Menu.objects.filter(parent_id=menu_obj.id).count()
    if menu_count > 0:
        return JsonResponse({'code': 201, 'msg':'该数据存在关联对象，不允许删除！'})
    try:
        menu_obj.delete()
    except Exception as e:
        return JsonResponse({'code': 202, 'msg': '删除对象失败！'})
    return JsonResponse({'code': 0, 'msg':'删除成功！'})

